import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Image ,Button} from '@tarojs/components'
import { staticUrl } from '@/utils'
import { connect } from 'react-redux'
import { getDistributionQrCode } from '@/api/distribution'
import { AtModal } from "taro-ui"

import './index.scss'
const p1 = staticUrl('/img/maintain/p1.png')
const p2 = staticUrl('/img/maintain/p2.png')
const weixin = 'https://static3.jekunauto.com/img/others/weixin.png'
const weixin1 = 'https://static3.jekunauto.com/img/others/weixin1.png'
const check_icon_2 = 'https://static3.jekunauto.com/img/others/check_icon_2.png'
const checked = 'https://static3.jekunauto.com/img/others/checked_1.png'
const check_icon_1 = 'https://static3.jekunauto.com/img/others/check_icon_1.png'
const upload_icon = staticUrl('/img/others/upload_icon.png')
const baoyang = staticUrl('/img/distribution/baoyang.png')
const luntai = staticUrl('/img/distribution/luntai.png')
const oilPulsP3 = staticUrl('/img/maintain/activity_1/v2/4.png')
const oilPulsP4 = staticUrl('/img/maintain/activity_1/v2/5.png')
const oilPulsP5 = staticUrl('/img/maintain/activity_1/v2/6.png')
const oilPulsP6 = staticUrl('/img/maintain/activity_1/v2/7.png')
const pqyTips = staticUrl('/img/distribution/pyq.png')
const tyrePuls0 = staticUrl('/img/maintain/activity_2/v2/1.png')
const tyrePuls1 = staticUrl('/img/maintain/activity_2/v2/2.png')
const tyrePuls2 = staticUrl('/img/maintain/activity_2/v2/3.png')
const tyrePuls3 = staticUrl('/img/maintain/activity_2/v2/4.png')


interface State {
  imgList: any,
  selectAll: boolean,
	oilPulsImgs:any,
	tyrePulsImgs:any,
	oilPulImgList:any,
	qrcodeImg:'',
	tips:boolean,
	type:any,
	openVisable:any
}

@connect<any>(({ location, car }) => ({ storeInfo: location.storeLocation, car: car.carInfo.currentCar }))
class Adviser extends Component<any> {
    $instance = getCurrentInstance();
    constructor (props) {
      super(props)
      this.state = {
              qrcodeImg:'',
              type:'',
              tips:false,
        selectAll: false,
              imgList:[],
              tyrePulsImgs:[
                  {
                      url: tyrePuls0,
                      select: false,
                      isQrcode: false
                  },{
                      url: tyrePuls1,
                      select: false,
                      isQrcode: false
                  },
                  {
                      url: tyrePuls2,
                      select: false,
                      isQrcode: false
                  },
                  {
                      url: tyrePuls3,
                      select: false,
                      isQrcode: false
                  }
              ],
              // imgList:[],
        oilPulsImgs: [
              {
          url: oilPulsP3,
          select: false,
          isQrcode: false
        },
              {
          url: oilPulsP4,
          select: false,
          isQrcode: false
        },
              {
          url: oilPulsP5,
          select: false,
          isQrcode: false
        },
              {
          url: oilPulsP6,
          select: false,
          isQrcode: false
        }],
              openVisable:false
      }
    }
    state: State
    componentDidMount() {
      const { distributionLeaderId,type } = this.$instance.router.params
          console.log('distributionLeaderId',distributionLeaderId)
          console.log('type',type)
          this.setState({
              type
          })
          this.getDistributionPoster({distributionLeaderId,type:type=='oil_puls' ? 2 : 3})
    }

    UNSAFE_componentWillReceiveProps() {
    }
    private car: ICar | {} = {}

    /**
    * 获取车险团长分享海报 type:1:邀请好友买车险 2:e保养+ 3:e轮胎+
    **/
    getDistributionPoster ({distributionLeaderId,type}) {
           getDistributionQrCode({
                   distributionLeaderId,
                   type
           }).then(res=>{
               let oilPulsImgs = this.state.oilPulsImgs
               let tyrePulsImgs = this.state.tyrePulsImgs
               // 'oil_puls':baoyang,
               // 'tyre_puls':luntai
               let imgList = type == 2 ? oilPulsImgs : tyrePulsImgs
               imgList.unshift({
                   url: res.data.data.url,
                   select: false,
                   isQrcode: true
               })
               this.setState({
                   imgList,
                   qrcodeImg:res.data.data.url
               })
               console.log('res',res)
           })
       }

    /**
     * 选中某一项
     */
    selectItem(index) {
      let { imgList, selectAll } = this.state
      imgList[index].select = !imgList[index].select
      selectAll = true
      imgList.forEach(e => {
        if (!e.select) {
          selectAll = false
        }
      })
      this.setState({
        imgList,
        selectAll,
              tips:false
      })
    }

    /**
     * 全选
     */
    checkAll(value) {
      let { imgList, selectAll } = this.state
      imgList.map(e => {
        e.select = value
        return e
      })
      this.setState({
        imgList,
        selectAll: value,
              tips:false
      })
    }
    // 下载图片
    downloadImg(shareImg) {
    Taro.getSetting({
      success: res => {
        Taro.authorize({
          scope: 'scope.writePhotosAlbum',
          success: res => {
            console.log('授权成功');
            let imgUrl = shareImg;
            console.log(imgUrl);
            Taro.downloadFile({  //下载文件资源到本地，客户端直接发起一个HTTP GET 请求，返回文件的本地临时路径
              url: imgUrl,
              success: res => {
                Taro.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath, //返回的临时文件路径，下载后的文件会存储到一个临时文件
                  success: res => {
                    Taro.showToast({
                      title: '成功保存到相册',
                      icon: 'success'
                    })
                  }
                })
              }
            })
          },
					fail:err=>{
						this.setState({
							openVisable:true
						})
					}
        })
      }
    })
  }

    openSaveImg(){
		Taro.openSetting().then(resp => {
				const status = resp.authSetting['scope.writePhotosAlbum']
				if (status) {
					Taro.showToast({
						title: '开启成功',
						icon: 'success'
					})
					this.setState({
						openVisable:false
					})
				}
		})
	}

    /**
     * 下载素材
     */
    saveImg() {
      let { imgList } = this.state
      let noDate = true
      imgList.forEach(e => {
        if (e.select) {
          noDate = false
                  this.downloadImg(e.url)
        }
      })
      if (noDate) {
        Taro.showToast({
          title: '未选择图片',
          icon: 'none'
        })
      }
    }

    closePyq(){
		this.setState({
			tips:false
		})
	}

    closeOpenVisable(){
		this.setState({
			openVisable:false
		})
	}

    /**
 * 朋友圈
 */
    handlePyq() {
        let {qrcodeImg} = this.state
        let _this = this
       Taro.getSetting({
           success: res => {
               Taro.authorize({
                   scope: 'scope.writePhotosAlbum',
                   success: res => {
                       console.log('授权成功')
                       let imgUrl = qrcodeImg
                       console.log(imgUrl);
                       Taro.downloadFile({  //下载文件资源到本地，客户端直接发起一个HTTP GET 请求，返回文件的本地临时路径
                           url: imgUrl,
                           success: res => {
                               Taro.saveImageToPhotosAlbum({
                                   filePath: res.tempFilePath, //返回的临时文件路径，下载后的文件会存储到一个临时文件
                                   success: res => {
                                       _this.setState({
                                           tips:true
                                       })
                                   }
                               })
                           }
                       })
                   },
                   fail:err=>{
                       this.setState({
                           openVisable:true
                       })
                   }
               })
           },
       })
   }


    onShareAppMessage() {
      let { type = '', distributionLeaderId = '' } = this.$instance.router.params
          let typeObj = {
              'oil_puls':'百店百万车主亿元补贴，全民免费保养!',
              'tyre_puls':'百店百万车主亿元补贴，全民免费保养'
          }
          let imgObj = {
              'oil_puls':baoyang,
              'tyre_puls':luntai
          }
          console.log('type',type)
          let path = `/insurance/upKeep/transact/puls`
          let query = {
              type
          }
          console.log(`pages/webview/index/index?path=${path}&distributionLeaderId=${distributionLeaderId}&query=${JSON.stringify(query)}`)
      return {
        title: `${typeObj[type]}`,
        // path: `pages/webview/index/index?path=${path}&distributionLeaderId=${distributionLeaderId}&query=${JSON.stringify(query)}`,
              path: `pages/maintain/activity_${type=='oil_puls'?1:2}/index?distributionLeaderId=${distributionLeaderId}&distributionLeaderUserId=${distributionLeaderId}`,
        imageUrl: imgObj[type]
      }
    }

    render() {
      const { imgList, selectAll ,tips,type,openVisable} = this.state
      return (
        <View className="container">
          <View className='module'>
            <View className="module-title">分享活动</View>
                      {
                          type == 'oil_puls' ? (
                              <Image className="share-example" src={p1}></Image>
                          ):null
                      }
                      {
                          type == 'tyre_puls' ? (
                              <Image className="share-example" src={p2}></Image>
                          ):null
                      }
            <View className="btn">
                      <Button className='share-btn' openType='share'>
              <Image className="icon" src={weixin}></Image>
              分享给好友
                          </Button>
            </View>

          </View>

          <View className="module">
            <View className="module-title"><Image className="select-icon" onClick={() => this.checkAll(selectAll ? false : true)} src={selectAll ? checked : check_icon_2}></Image>全选</View>
            <View className="image-list">
              {
                imgList.map((e, index) => {
                  return (
                    <View className="image-item" onClick={() => this.selectItem(index)}>
                      <Image className="check_icon" src={e.select ? checked : check_icon_1}></Image>
                      <Image className="thumbImg" src={e.url} mode="aspectFill"></Image>
                      {e.isQrcode && <View className="tip">带二维码图片</View>}
                    </View>
                  )
                })
              }
            </View>
          </View>

          <View className="footer">
            <View className="btn" onClick={() => this.handlePyq()}>
              <Image className="icon" src={weixin1}></Image>
              朋友圈
            </View>
            <View className="btn" onClick={() => this.saveImg()}>
              <Image className="icon" src={upload_icon}></Image>
              保存素材
            </View>
          </View>
                  <AtModal isOpened={tips} closeOnClickOverlay>
                      <View className="tips-wrap">
                          <Image className="tips-img" mode="widthFix" src={pqyTips} />
                      </View>
                  </AtModal>
                  {
                      openVisable ? (
                          <View className="dialog-wrap" >
                              <View className="dialog-bg" onClick={this.closeOpenVisable}></View>
                              <View className="dialog-mask">
                                  <View className="dialog-tips">请先开启保存相册的权限</View>
                                  <View className="open-btn" onClick={this.openSaveImg}>开启权限</View>
                              </View>
                          </View>
                      ):null
                  }

        </View>
      )
    }
}
export default Adviser
